//
//  NewsDetailViewController.swift
//  MyNews
//
//  Created by DF-Mac on 16/12/13.
//  Copyright © 2016年 DF-Mac. All rights reserved.
//

import UIKit
import WebKit

class NewsDetailViewController: UIViewController,WKNavigationDelegate,WKUIDelegate {

    var newsUrl : String?
    
    var wkWebView : WKWebView?
    //前进后退按钮
    var btnBack = UIBarButtonItem()
    var btnForward = UIBarButtonItem()
    //进度条
    var progBar = UIProgressView()
    override func viewWillDisappear(_ animated: Bool) {
          wkWebView?.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        
        
        self.initialUI()
        
        
        // Do any additional setup after loading the view.
    }
    private func loadData() -> () {
        guard let newsurl=newsUrl else {
            print("新闻链接为空")
            return
        }
        print(newsurl)
        let url = URL(string: newsurl)
        
//        let url = URL(string:"http://www.baidu.com")
        
        
        let request=URLRequest(url: url!)
        _=wkWebView?.load(request)
    }
    private func initialUI() -> () {
        //wkWebView
        wkWebView = WKWebView(frame: view.bounds)
        
        view.addSubview(wkWebView!)
        
        wkWebView?.navigationDelegate=self
        wkWebView?.uiDelegate=self
        //进度条
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 30))
        

        progBar.progress = 0.0
        progBar.tintColor = UIColor.red
        wkWebView?.addSubview(progBar)
        
        wkWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
//        wkWebView.
//        webView.delegate=self
        self.loadData()
        self.setNavBar()
    
    }

    private func setNavBar() -> () {
        btnBack = UIBarButtonItem(title: "后退", style: .plain, target: self, action: #selector(toBack))
        btnForward = UIBarButtonItem(title: "前进", style: .plain, target: self, action: #selector(toForward))
        
//        navigationItem.rightBarButtonItem=btnBack
        navigationItem.rightBarButtonItems=[btnBack,btnForward]
    }
    
    //返回
    func toBack() -> () {
        if (wkWebView?.canGoBack)! {
            _=wkWebView?.goBack()
        }
    }
    //前进
    func toForward() -> () {
        if (wkWebView?.canGoForward)! {
            _=wkWebView?.goForward()
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    ///WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        navigationItem.title=webView.title
    }
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        //如果目标主视图不为空,则允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            _=wkWebView?.load(navigationAction.request)
        }
        return nil
    }
    
    // 监听通过JS调用警告框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    // 监听通过JS调用提示框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler(true)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
            completionHandler(false)
        }))
        self.present(alert, animated: true, completion: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath=="estimatedProgress" {
            progBar.alpha=1.0
            progBar.setProgress(Float((wkWebView?.estimatedProgress)!), animated: true)
            
            guard let ep=wkWebView?.estimatedProgress else {
                return
            }
            //print(ep)
            if ep >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { 
                    () in
                    self.progBar.alpha=0.0
                    }, completion: { (finished:Bool) in
                        self.progBar.progress = 0
                })
            }
        }
    }
//    - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
//    
//    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
